<?php

namespace App\Console\Commands;

use App\Exceptions\MissParamException;
use App\Libs\BLogger;
use App\Models\AlimamaOrder;
use App\Models\OrderBill;
use App\Models\OrderCommission;
use App\Models\PidOrder;
use App\Models\User;
use App\Models\UserPid;
use Illuminate\Console\Command;

class TaokeOrderBill extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'taoke-order-bill';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '淘客订单结算';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $date  = date('Y-m-d', time());
        $day   = date('d', time());

        if ($day >= 21) {
            $startMonth = date('Y-m', strtotime("$date"));
        } else {
            $startMonth = date('Y-m', strtotime("$date -1 month"));
        }

        $withdrawCashTime = $startMonth . '-01';
        try {
            $userPidModel = new UserPid();
            $userModel = new User();
            $pidOrder = new PidOrder();
            $orderModel = new AlimamaOrder();
            $billModel = new OrderBill();
            $orderCommissionModel = new OrderCommission();

            $order = \DB::table($orderModel->getTable() . ' as o')
                ->select(
                    'o.*',
                    'u.id as uid',
                    'u.father_id',
                    'u.agent_level1_rate',
                    'u.agent_level2_rate',
                    'u.bill_order_num',
                    'u.agent_num'
                )
                ->leftJoin($pidOrder->getTable() . ' as po', 'po.order_id', '=', 'o.id')
                ->leftJoin($userPidModel->getTable() . ' as up', 'up.pid_id', '=', 'po.pid_id')
                ->leftJoin($userModel->getTable() . ' as u', 'u.id', '=', 'up.user_id')
                ->leftJoin($billModel->getTable() . ' as b', 'b.order_id', '=', 'o.id')
                ->whereNull('b.id')
                ->whereIn('o.status', [\Config::get('app.alimama_order.status.payment'), \Config::get('app.alimama_order.status.settlement'), \Config::get('app.alimama_order.status.complete')])
                ->lockForUpdate()
                ->get();

            foreach ($order as $o) {
                $commission = [
                    'commission1' => 0,
                    'commission2' => 0
                ];
                \DB::beginTransaction();
                try {
                    if (
                        $o->status == \Config::get('app.alimama_order.status.settlement')
                        || $o->status == \Config::get('app.alimama_order.status.complete')
                    ) {
                        //已结算订单
                        $commission['commission1'] = bcmul(bcadd($o->commission_amount, $o->subsidy_amount, 3), $o->agent_level1_rate, 3);
                        $commission['commission2'] = bcmul(bcadd($o->commission_amount, $o->subsidy_amount, 3), $o->agent_level2_rate, 3);

                        //这里要实际结算的时候执行

                        if($o->create_time < $withdrawCashTime) {
                            //记录已结算的订单
                            if (\DB::table($billModel->getTable())->insert([
                                    'uid' => $o->uid,
                                    'order_id' => $o->id,
                                    'commission' => $commission['commission1']
                                ]) === false) {
                                \DB::rollBack();
                                BLogger::getLogger('ORDER_BILL')->warning("更新结算表失败,uid:{$o->uid},使用commission1,commission:" . json_encode($commission));
                            }

                            //更新用户账户
                            if (\DB::table($userModel->getTable())->where('id', $o->uid)->update([
                                    'balance' => \DB::raw("balance + {$commission['commission1']}"),
                                    'commission' => \DB::raw("commission+{$commission['commission1']}"),
                                    'bill_order_num' => \DB::raw("bill_order_num+1"),
                                ]) === false) {
                                \DB::rollBack();
                                BLogger::getLogger('ORDER_BILL')->warning("更新{$o->uid}账户失败,使用commission1,commission:" . json_encode($commission));
                            }

                            //更新上级代理账户
                            if ($o->father_id) {
                                if (\DB::table($userModel->getTable())->where('id', $o->father_id)->update([
                                        'balance' => \DB::raw("balance + {$commission['commission2']}"),
                                        'commission' => \DB::raw("commission+{$commission['commission2']}")
                                    ]) === false) {
                                    \DB::rollBack();
                                    BLogger::getLogger('ORDER_BILL')->warning("更新{$o->father_id}账户失败,使用commission2,commission:" . json_encode($commission));
                                }

                                if (\DB::table($billModel->getTable())->insert([
                                        'uid' => $o->father_id,
                                        'order_id' => $o->id,
                                        'commission' => $commission['commission2']
                                    ]) === false) {
                                    \DB::rollBack();
                                    BLogger::getLogger('ORDER_BILL')->warning("更新结算表失败,uid:{$o->father_id},使用commission2,commission:" . json_encode($commission));
                                }
                            }

                            //用户升级
                            $userBlock = new \App\Blocks\User();
                            if ($userBlock->userUpgrade($o->uid) === false) {
                                \DB::rollBack();
                                BLogger::getLogger('ORDER_BILL')->info("用户升级失败;uid:{$o->uid}");
                            }
                        }
                    } else {
                        //未结算订单
                        $commission['commission1'] = bcmul($o->expected_profit, $o->agent_level1_rate, 3);
                        $commission['commission2'] = bcmul($o->expected_profit, $o->agent_level2_rate, 3);
                    }

                    //更新订单佣金表
                    if (\DB::table($orderCommissionModel->getTable())->updateOrInsert([
                            'order_id' => $o->id
                        ], $commission) === false
                    ) {
                        BLogger::getLogger('ORDER_BILL')->info("计算订单的佣金,可能已经存在;order_id:{$o->id},commission:" . json_encode($commission));
                    } else {
                        BLogger::getLogger('ORDER_BILL')->info("计算订单的佣金;order_id:{$o->id},commission:" . json_encode($commission));
                    }
                    \DB::commit();
                    BLogger::getLogger('ORDER_BILL')->info("结算成功;order_id:{$o->id}");
                } catch (\Exception $exception) {
                    \DB::rollBack();
                    BLogger::getLogger('ORDER_BILL')->error($exception);
                }
            }
        }catch (\Exception $exception){
            BLogger::getLogger('ORDER_BILL')->error($exception);
        }
        return;
    }
}